package com.wish.group05.house.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import com.wish.group05.base.dto.RoomInfoDTO;
import com.wish.group05.base.entity.HouseInfo;
import com.wish.group05.base.entity.RoomInfo;
import com.wish.group05.base.service.IHouseInfoService;
import com.wish.group05.base.service.IRoomInfoService;
import com.wish.group05.base.vo.*;
import com.wish.group05.common.core.utils.StringUtils;
import com.wish.group05.common.core.web.controller.BaseController;
import com.wish.group05.common.core.web.domain.AjaxResult;
import com.wish.group05.common.core.web.page.TableDataInfo;
import com.wish.group05.common.security.utils.SecurityUtils;
import com.wish.group05.house.enums.ConditionType;
import com.wish.group05.house.service.ITbRoomInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author xuekai
 * @date 2022-05-30
 */
@Service
public class TbRoomInfoServiceImpl extends BaseController implements ITbRoomInfoService
{

    @Autowired
    private IRoomInfoService iRoomInfoService;

    @Autowired
    private IHouseInfoService iHouseInfoService;

    @Override
    public AjaxResult editRecommended(RoomInfoDTO roomInfoDTO) {

        List<String> ids = roomInfoDTO.getIds();
        ArrayList<RoomInfo> arrayList = new ArrayList<>();
        ids.forEach(id->{
            RoomInfo roomInfo = new RoomInfo();
            roomInfo.setId(id).setRecommended(roomInfoDTO.getRecommended());
            arrayList.add(roomInfo);
        });
        boolean b = iRoomInfoService.updateBatchById(arrayList);
        if(b){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public TableDataInfo roomAvailabilityFigure(RoomInfoDTO roomInfoDTO) {
        //分散式房源
        if(roomInfoDTO.getHostType()==0){
            List<RoomInfoVO> list = iRoomInfoService.getDisperseList(roomInfoDTO);
            TableDataInfo dataTable = getDataTable(list);
            List<RoomInfoVO> rows = (List<RoomInfoVO>) dataTable.getRows();
            List<TbRoomInfoFsVO> res=null;
            if(rows.size()>0){
                res=pushRecordMini(rows,roomInfoDTO.getPreName());
            }
            System.out.println(res);
            dataTable.setRows(res);
            return dataTable;
        }
        //集中式房源
        List<RoomInfoVO> list = iRoomInfoService.getJzList(roomInfoDTO);
        TableDataInfo dataTable = getDataTable(list);
        List<RoomInfoVO> rows = (List<RoomInfoVO>) dataTable.getRows();
        if (rows.size() > 0) {
            //roomInfoDTO.setHouseId(list.get(0).getHouseId());
            rows = iRoomInfoService.findPageListDetailByJz(roomInfoDTO);
        }
        //集中公寓
        List<TbRoomInfoJzGyVO> tbRoomInfoJzGyVO = null;
        if (rows.size() > 0) {
            tbRoomInfoJzGyVO=pushJzRecord(rows,roomInfoDTO.getPreName());
        }
        dataTable.setRows(tbRoomInfoJzGyVO);
        return dataTable;
    }

    @Override
    public AjaxResult updatePublishStatus(RoomInfoDTO roomInfoDTO) {

        //状态为空情况下删除
        if(roomInfoDTO.getPublishStatus()==null){
            HouseInfo houseInfoInfo = new HouseInfo();
            houseInfoInfo.setId(roomInfoDTO.getHouseId())
                    .setStatus(1);
            boolean b = iHouseInfoService.updateById(houseInfoInfo);
            if(b){
                return AjaxResult.success();
            }
            return AjaxResult.error();
        }

        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setId(roomInfoDTO.getHouseId())
                .setPublishStatus(Integer.parseInt(roomInfoDTO.getPublishStatus()))
                .setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //修改为发布
        if(roomInfoDTO.getPublishStatus().equals(1)){
            houseInfo.setCreateBy(SecurityUtils.getUsername())
                    .setUpdateTime(new Date());
        }
        //修改为未发布
        boolean b = iHouseInfoService.updateById(houseInfo);
        if(b){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 计算 - 集中式房源赋值
     * @param rows
     * @param preName
     * @return
     */
    private List<TbRoomInfoJzGyVO> pushJzRecord(List<RoomInfoVO> rows, String preName) {
        Map<String, Integer> countMap = new HashMap<>();
        Map<String, Integer> numMap = new HashMap<>();
        List<TbRoomInfoJzGyVO> gy = new ArrayList<>(); // 公寓s
        List<TbRoomInfoJzLdVO> ld = new ArrayList<>(); // 楼栋s
        List<TbRoomInfoJzLcVO> lc = new ArrayList<>(); // 楼层s
        List<TbRoomInfoMiniVO> fy; // 房源s
        TbRoomInfoJzGyVO g;
        TbRoomInfoJzLdVO d;// 楼栋
        TbRoomInfoJzLcVO c;// 楼层
        Set<String> gySet = new HashSet<>();
        Set<String> ldSet = new HashSet<>();
        Set<String> lcSet = new HashSet<>();
        Set<String> mkey = new HashSet<>();
        Map<String, List<TbRoomInfoJzLdVO>> ldMap = new HashMap<>();
        Map<String, List<TbRoomInfoJzLcVO>> lcMap = new HashMap<>();
        Map<String, List<TbRoomInfoMiniVO>> fyMap = new HashMap<>();

        for (RoomInfoVO m : rows) {
            String gyConKey = m.getHouseId();
            // 初始公寓
            if (!gySet.contains(gyConKey)) {
                g = new TbRoomInfoJzGyVO();
                BeanUtils.copyProperties(m,g);
                g.setFindFlatName(subHig(g.getFlatName(), preName));
                g.setPreName(subHig(g.getPreName(), preName));
                gy.add(g);
                gySet.add(gyConKey);
            }
            // 初始楼栋
            String ldConsKey = m.getHouseId() + "-" + m.getBuildingName();
            if (!ldSet.contains(ldConsKey)) {
                d = new TbRoomInfoJzLdVO();
                d.setBuildingName(subHig(m.getBuildingName(),preName));
                d.setHouseId(m.getHouseId());
                ld.add(d);
                ldSet.add(ldConsKey);
            }
            // 初始楼层
            String lcConsKey = m.getHouseId() + "-" + m.getBuildingName() + "-" + m.getFloor();
            if (!lcSet.contains(lcConsKey)) {
                c = new TbRoomInfoJzLcVO();
                c.setBuildingName(m.getBuildingName());
                c.setFloor(subHig(m.getFloor()+"",preName));
                c.setHouseId(m.getHouseId());
                lc.add(c);
                lcSet.add(lcConsKey);
            }
            if (!mkey.contains(m.getRoomId()) || null != m.getRcDates()) {
                TbRoomInfoMiniVO mini = getComputeRoomMini(m,preName);
                mini.setRoomCode(subHig(mini.getRoomCode(), preName));
                if (null != mini.getRoomId()) {
                    String putKey = mini.getHouseId() + "-" + mini.getBuildingName() + "-" + mini.getFloor();
                    List<TbRoomInfoMiniVO> list = fyMap.get(putKey);
                    if (null != list) {
                        // this.checkMini(mini, list);
                        fyMap.get(putKey).add(mini);

                    } else {
                        fy = new ArrayList<>();
                        fy.add(mini);
                        fyMap.put(putKey, fy);
                    }
                    // 记录时间
                    String countKey = mini.getHouseId() + "-" + mini.getBuildingName();
                    Integer count = countMap.get(countKey);
                    if (null == count) {
                        if (!mkey.contains(m.getRoomId())) {
                            countMap.put(countKey, 1);
                        }
                    }else {
                        if (!mkey.contains(m.getRoomId())) {
                            count++;
                            countMap.put(countKey, count);
                        }
                    }
                    if (mini.getLeisureFlag() == 1) {
                        Integer num = numMap.get(countKey);
                        if (null == num) {
                            numMap.put(countKey, 1);
                        } else {
                            num++;
                            numMap.put(countKey, num);
                        }
                    }
                }
                mkey.add(m.getRoomId());
            }
        }
        List<TbRoomInfoJzLcVO> lcTemp;
        // 计算楼层
        for (TbRoomInfoJzLcVO l : lc) {
            String getkKey = l.getHouseId() + "-" + l.getBuildingName() + "-" + l.getFloor();
            List<TbRoomInfoMiniVO> list = fyMap.get(getkKey);
            if (null != list && list.size() > 0) {
                l.setMiniDetail(list);
                String key = l.getHouseId() + "-" + l.getBuildingName();
                if (null != lcMap.get(key)) {
                    lcMap.get(key).add(l);
                } else {
                    lcTemp = new ArrayList<>();
                    lcTemp.add(l);
                    lcMap.put(key, lcTemp);
                }
            }
        }
        List<TbRoomInfoJzLdVO> ldTemp;
        // 计算楼栋
        for (TbRoomInfoJzLdVO ds : ld) {
            String getKey = ds.getHouseId() + "-" + ds.getBuildingName();
            List<TbRoomInfoJzLcVO> list = lcMap.get(getKey);
            if (null != list && list.size() > 0) {
                ds.setMiniDetail(list);
                if (null != countMap.get(getKey)) {
                    ds.setTotal(countMap.get(getKey));
                }
                if (null != numMap.get(getKey)) {
                    ds.setVacancyNum(numMap.get(getKey));
                }

                if (null != ldMap.get(ds.getHouseId())) {
                    ldMap.get(ds.getHouseId()).add(ds);
                } else {
                    ldTemp = new ArrayList<>();
                    ldTemp.add(ds);
                    ldMap.put(ds.getHouseId(), ldTemp);
                }
            }
        }
        // 计算公寓
        for (TbRoomInfoJzGyVO gs : gy) {
            List<TbRoomInfoJzLdVO> list = ldMap.get(gs.getHouseId());
            if (null != list && list.size() > 0) {
                gs.setLdDetail(list);
            }
        }
        return gy;
    }

    /**
     * 计算分散式
     * @param list
     * @param preName
     * @return
     */
    private List<TbRoomInfoFsVO> pushRecordMini(List<RoomInfoVO> list, String preName) {
        Set<String> roomKeySet = new HashSet<>();
        Set<String> miniKey = new HashSet<>();
        Map<String, List<TbRoomInfoMiniVO>> miniMap = new HashMap<>();
        List<TbRoomInfoFsVO> res = new ArrayList<>();
        List<TbRoomInfoFsVO> ho = new ArrayList<>();
        List<TbRoomInfoMiniVO> miniTemp;
        for (RoomInfoVO r : list) {
            //楼盘id和房源id
            String key = r.getPreId() + "-" + r.getHouseId();
            //判断集合不包含
            if(!roomKeySet.contains(key)){
                TbRoomInfoFsVO tbRoomInfoFsVO = new TbRoomInfoFsVO();
                StringBuffer buffer = new StringBuffer();
                //拼接栋
                if(StringUtils.isNotBlank(r.getBuildingNo())){
                    buffer.append(subHig(r.getBuildingNo(),preName) + "栋");
                }
                //拼接单元
                if (StringUtils.isNotBlank(r.getUnitNo())) {
                    buffer.append(subHig(r.getUnitNo(),preName) + "单元");
                }
                //拼接房间号
                if (StringUtils.isNotBlank(r.getRoomNo())) {
                    buffer.append(subHig(r.getRoomNo(),preName));
                }
                //把拼接的设置进属性
                if (StringUtils.isNotBlank(buffer)) {
                    r.setBdiNo(buffer.toString());
                }
                tbRoomInfoFsVO.setRoomCount(r.getRoomCount());
                BeanUtils.copyProperties(r,tbRoomInfoFsVO);
                ho.add(tbRoomInfoFsVO);
                roomKeySet.add(key);
            }

            //计算初始房源
            TbRoomInfoMiniVO tbRoomInfoMiniVO=getComputeRoomMini(r,preName);
            if (null != tbRoomInfoMiniVO.getRoomId()) {
                tbRoomInfoMiniVO.setRoomCode(subHig(tbRoomInfoMiniVO.getRoomCode(),preName));
                String putKey = tbRoomInfoMiniVO.getHouseId();
                List<TbRoomInfoMiniVO> list1 = miniMap.get(putKey);
                if (null != list1) {
                    // this.checkMini(mini, list);
                    miniMap.get(putKey).add(tbRoomInfoMiniVO);
                } else {
                    miniTemp = new ArrayList<>();
                    miniTemp.add(tbRoomInfoMiniVO);
                    miniMap.put(putKey, miniTemp);
                }
                miniKey.add(r.getRoomId());
            }

        }

        // 房产
        for (TbRoomInfoFsVO s : ho) {
            String getKey = s.getHouseId();
            List<TbRoomInfoMiniVO> list2 = miniMap.get(getKey);
            if (null != list2 && list2.size() > 0) {
                s.setRoomCount(list2.size());
                s.setRoomMni(list2);
                s.setFindPreName(subHig(s.getPreName(),preName));
                res.add(s);
            }
        }
        return res;
    }

    /**
     * 计算 - 房源状态
     * @param roomInfoVO
     * @param preName
     * @return
     */
    private TbRoomInfoMiniVO getComputeRoomMini(RoomInfoVO roomInfoVO, String preName) {
        TbRoomInfoMiniVO tbRoomInfoMiniVO = new TbRoomInfoMiniVO();
        List<Map<String, Object>> dList;
        Map<String, Object> dmap;
        int roomStatus = roomInfoVO.getRoomStatus();
        if (1 == roomStatus) { // 已租出
            dList = new ArrayList<>();
            int cEndDate = 0;
            int rcDate = 0;
            if (null != roomInfoVO.getCEndDate()) {
                cEndDate = Integer.parseInt(roomInfoVO.getCEndDate());// 合同天数
            }
            if (null != roomInfoVO.getRcDates()) {
                rcDate = Integer.parseInt(roomInfoVO.getRcDates());// 付款天数
            }
            // 计算租金日期
            if (0 < rcDate && rcDate <= 10) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.SHOUFEI.getIndex()); // 收费
                dmap.put("total", Math.abs(rcDate));
                dList.add(dmap);
            } else if (rcDate < 0) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.QIANFEI.getIndex()); // 欠费
                dmap.put("total", Math.abs(rcDate));
                dList.add(dmap);
            }
            // 计算合同
            if (0 < cEndDate && cEndDate <= 30) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.KUAIDAO.getIndex()); // 快到
                dmap.put("total", Math.abs(cEndDate));
                dList.add(dmap);
                if (roomInfoVO.getCheckTerm() == 0) { // 可续约
                    roomInfoVO.setCheckTerm(6);
                } else if (cEndDate < 0) {
                    dmap = new HashMap<>();
                    dmap.put("FangtaiType", ConditionType.DAOQI.getIndex()); // 到期
                    dmap.put("total", Math.abs(cEndDate));
                    dList.add(dmap);
                }
            }
            if (null == roomInfoVO.getCEndDate() && null == roomInfoVO.getRcDates()) {
                dmap = new HashMap<>();
                dmap.put("FangtaiType", ConditionType.YIDENGJI.getIndex()); // 已登记
                dList.add(dmap);
                roomInfoVO.setCheckRegister(1);
            }
            roomInfoVO.setMiniDetail(dList);

        } else if (2 == roomStatus) {// 装修中
            dList = new ArrayList<>();
            dmap = new HashMap<>();
            double finishDate = 0l;
            if (null != roomInfoVO.getFinishDate()) {
                finishDate = Integer.parseInt(roomInfoVO.getFinishDate());
            }
            if (finishDate != 0) {
                dmap.put("FangtaiType", ConditionType.ZHUANGXIU.getIndex());// 房态类型 装修
                dmap.put("total", Math.abs(finishDate));// 天数
                dList.add(dmap);
            }
            roomInfoVO.setMiniDetail(dList);
        } else if (0 == roomStatus) { // 0 默认 待租中（空置）
            dList = new ArrayList<>();
            dmap = new HashMap<>();
            Integer vacancyDate = 0;
            if (null != roomInfoVO.getVacancyDate()) {
                vacancyDate = Integer.parseInt(roomInfoVO.getVacancyDate());
            }
            if (vacancyDate != 0) {
                dmap.put("FangtaiType", ConditionType.KONGZHI.getIndex());// 房态类型 空置
                dmap.put("total", Math.abs(vacancyDate));// 天数
                dList.add(dmap);
                roomInfoVO.setLeisureDate(Math.abs(vacancyDate));
            }
            roomInfoVO.setLeisureFlag(1);
            roomInfoVO.setMiniDetail(dList);
        }
        BeanUtils.copyProperties(roomInfoVO,tbRoomInfoMiniVO);
        tbRoomInfoMiniVO.setTenantName(subHig(tbRoomInfoMiniVO.getTenantName(), preName));
        return tbRoomInfoMiniVO;
    }

    /**
     * 高亮显示 - 条件字段
     * @param buildingNo
     * @param preName
     * @return
     */
    private String subHig(String buildingNo, String preName) {
        if (StringUtils.isNotBlank(preName) && StringUtils.isNotBlank(buildingNo)) {
            String temp = null;
            temp = buildingNo;
            StringBuffer buf = new StringBuffer();
            int indexOf;
            String start = null;
            String end = null;
            while (temp.toUpperCase().indexOf(preName.toUpperCase()) != -1) {
                indexOf = temp.indexOf(preName);
                start = temp.substring(0, indexOf);
                end = temp.substring(indexOf + preName.length(), temp.length());
                buf.append(start);
                buf.append("<font color='red' >" + preName + "</font>");
                temp = end;
            }
            if (end == null) {
                buf.append(temp);
            } else {
                buf.append(end);
            }
            return buf.toString();
        } else {
            return buildingNo;
        }
    }
}
